import BaseButton from '@/components/base/BaseButton';
import BaseForm, {
  BaseFormSelect,
  ProFormDateTimePicker,
  ProFormDependency,
  ProFormInstance
} from '@/components/base/BaseForm';
import BasePageFrame from '@/components/base/BasePageFrame';
import { getList as getRadarList } from '@/pages/radar/RadarInfo/api';
import { getList as getRadarTypeList } from '@/pages/radar/RadarTypeInfo/api';
import useUserStore from '@/store/user';
import { useRequest } from '@/utils/request';
import { Alert, Card, Col, ConfigProvider, Empty, message, Row, Spin } from 'antd';
import { useRef, useState } from 'react';
import { getData, saveData } from '../api';
import { DataSimulationModel } from '../data';

const DataSimulation = () => {
  const form = useRef<ProFormInstance>();
  const startRef = useRef(false);
  const [simulationData, setSimulationData] = useState<DataSimulationModel>({
    simulationDataType: 2
  } as DataSimulationModel);
  const simulation = useRequest(getData, {
    pollingInterval: 1000 * 60 * 5,
    pollingWhenHidden: true,
    onSuccess([data]) {
      if (data) {
        startRef.current = data.state === 1;
        setSimulationData(data);
        form.current?.setFieldsValue(data);
      } else {
        startRef.current = false;
        setSimulationData({ simulationDataType: 2 } as DataSimulationModel);
        form.current?.setFieldsValue({});
      }
    }
  });
  const save = useRequest(saveData, {
    manual: true,
    onSuccess() {
      simulation.run();
    }
  });
  const { userinfo } = useUserStore.getState();
  const isStart = simulationData.state === 1;
  const mode = isStart ? 'read' : 'edit';
  return (
    <BasePageFrame>
      <Card style={{ height: '100%' }}>
        <Row>
          <Col offset={6} span={12}>
            <Spin spinning={simulation.loading}>
              <BaseForm
                formRef={form}
                labelCol={{ style: { width: 80 } }}
                layout='horizontal'
                submitter={{
                  render: (props) => {
                    return (
                      <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                        {
                          // eslint-disable-next-line no-nested-ternary
                          !isStart ? (
                            <BaseButton
                              type='primary'
                              block
                              loading={simulation.loading || save.loading}
                              onClick={async () => {
                                await simulation.run();
                                console.log(!startRef.current, props.submit);
                                if (!startRef.current) {
                                  props.submit();
                                } else {
                                  message.warning('当前已存在开始的仿真，无法再次开始');
                                }
                              }}
                            >
                              开始仿真
                            </BaseButton>
                          ) : userinfo.username === simulationData.creator ? (
                            <BaseButton
                              block
                              danger
                              loading={save.loading}
                              onClick={async () => {
                                const ok = await save.run({ ...simulationData, state: 0 });
                                if (ok) {
                                  message.success('仿真结束成功');
                                }
                              }}
                            >
                              结束仿真
                            </BaseButton>
                          ) : (
                            <Alert
                              type='warning'
                              message={`当前仿真由用户 ${simulationData.creator} 开启，您无法结束由其他用户开始的仿真`}
                            />
                          )
                        }
                      </div>
                    );
                  }
                }}
                onFinish={async (values) => {
                  values.state = 1;
                  values.simulationDataType = 2;
                  const ok = await save.run(values);
                  if (ok) {
                    message.success('仿真开始成功');
                  }
                }}
              >
                <h2>{isStart ? '' : '请选择'}仿真模型参数</h2>
                <BaseFormSelect
                  label='雷达型号'
                  name='radarTypeId'
                  request={getRadarTypeList}
                  placeholder='请选择雷达型号'
                  readonly={isStart}
                  fieldProps={{
                    fieldNames: { label: 'name', value: 'id' },
                    defaultSelectedOptions: [
                      { name: simulationData.radarTypeName, id: simulationData.radarTypeId }
                    ],
                    onChange() {
                      form.current?.setFieldsValue({ radarId: undefined });
                    }
                  }}
                  rules={[{ required: !isStart, message: '请选择雷达型号' }]}
                />
                <ProFormDependency name={['radarTypeId']}>
                  {({ radarTypeId }) => {
                    return (
                      <ConfigProvider
                        renderEmpty={() => (
                          <Empty
                            image={Empty.PRESENTED_IMAGE_SIMPLE}
                            description='暂无可进行仿真的雷达，请检查雷达类型下有绑定雷达，且雷达已有数据表'
                          />
                        )}
                      >
                        <BaseFormSelect
                          label='雷达'
                          name='radarId'
                          placeholder='请选择雷达'
                          readonly={isStart}
                          hiddenItem={!radarTypeId}
                          hiddenRender={() => <Alert type='warning' message='请先选择雷达型号' />}
                          params={{ typeId: radarTypeId, isRUL: 1 }}
                          fieldProps={{
                            fieldNames: { label: 'name', value: 'id' },
                            defaultSelectedOptions: [
                              { name: simulationData.radarName, id: simulationData.radarId }
                            ]
                          }}
                          request={getRadarList}
                          rules={[
                            {
                              required: !isStart,
                              message: radarTypeId ? '请选择雷达' : '请先选择雷达型号'
                            }
                          ]}
                        />
                      </ConfigProvider>
                    );
                  }}
                </ProFormDependency>
                <Row gutter={16}>
                  <Col span={12}>
                    <ProFormDateTimePicker
                      label='开始时间'
                      name='startDataTime'
                      proFieldProps={{ mode }}
                      fieldProps={{
                        style: { width: '100%' }
                      }}
                      placeholder='请选择数据源开始时间'
                      rules={[{ required: !isStart, message: '请选择数据源开始时间' }]}
                    />
                  </Col>
                  <Col span={12}>
                    <ProFormDateTimePicker
                      label='结束时间'
                      name='endDataTime'
                      placeholder='请选择数据源结束时间'
                      proFieldProps={{ mode }}
                      fieldProps={{ style: { width: '100%' } }}
                      rules={[{ required: !isStart, message: '请选择数据源结束时间' }]}
                    />
                  </Col>
                </Row>
              </BaseForm>
            </Spin>
          </Col>
        </Row>
      </Card>
    </BasePageFrame>
  );
};

export default DataSimulation;
